/*
 *This file will contain all the functions that have to do with
 communicating with the command socket.  These functions will be handled by
 thread 1.
 */

#include "dataSockFuncs.h"

void *dataSocketCom(void *notUsed)
{

	for(;;)
	{
		pthread_cond_wait(&listBufRdy, &mListBuf); //wait for thread 0 to signal...
		
		if(shouldExit)
			break;


		//if list buf contains an "l", read a directory listing
		if(!strcmp("l", listBuf))
		{
		
			listBuf = (char*) readFully(data_socket);
			pthread_cond_signal(&listBufRdy);

		}
		else if(strstr(listBuf, "d "))
		{
			char *strPtr;
			strtok_r(listBuf, " ", &strPtr);
			
			downloadFile(strtok_r(NULL, " ", &strPtr));
		}
		pthread_mutex_lock(&dummyMutex);
		pthread_mutex_unlock(&dummyMutex);
		pthread_cond_signal(&enterPasvMode);
		

	}
	pthread_exit(NULL);
	return NULL;
}

//This function downloads a given file
void downloadFile(char *fileName)
{

	listBuf = chk_malloc(5);

	sprintf(listBuf, "0%%");

	//memory buffer for file
	void *buf[DATA_BUF_SIZE];

	//will point to the file
	FILE *f;

	//will store number of bytes read in one iteration
	//and total bytes read so far, respectively
	int bytesRead, bytesReadSoFar = 0;

	if((f = fopen(fileName, "w")) == NULL){
		perror("Failed to open file");
		exit(1);
	}
	

	while((bytesRead = read(data_socket, buf, DATA_BUF_SIZE)))
	{

		//write downloaded data to disk
		if(fwrite(buf, bytesRead, 1, f) < 1){
			perror("Error Writing to File");
			exit(1);
		}
		bytesReadSoFar += bytesRead;


		
	}

	fclose(f);

	//by changing fileSize to -1, we are signaling to thread 0 that downloading is done
	fileSize = -1;
	pthread_mutex_unlock(&mFileSize);
	//pthread_mutex_lock(&mListBuf);

}
